package kafka_day02

import java.sql.{Connection, DriverManager, PreparedStatement, SQLException}

object MysqlTransactionTest {

  def main(args: Array[String]): Unit = {


    var conn: Connection = null
    var ps1: PreparedStatement = null
    var ps2: PreparedStatement = null

    try {
      //创建数库链接
       conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/guanxi?characterEnconding=utf-8", "root", "123456")
      //开启事务
      conn.setAutoCommit(false)

      ps1 = conn.prepareStatement("insert into t_wordcount (word,counts) values(?,?)")
      ps1.setString(1, "dehua")
      ps1.setInt(2, 12)
      ps1.executeUpdate()

      //val i = 1 / 0

      ps2 = conn.prepareStatement("INSERT INTO t_kafka_offset (app_gid, topic_partition, offset) VALUES (?, ?, ?)")
      ps2.setString(1, "test1_g001")
      ps2.setString(2, "wc_0")
      ps2.setInt(3, 30)

      ps2.executeUpdate()
      println("2 sql execute")
      //提交事物
      conn.commit()
    } catch {
      case e: Exception => {
        println("has a erro")

       conn.rollback()
      }

    } finally {
      if (ps1 != null) {

        ps1.close()

      }
      if (ps2 != null) {

        ps2.close()

      }
      if (conn != null) {

        conn.close()

      }

      println("success")

    }


  }


}
